let topPlayList = require('../api/netease/top_playlist');
let playlist_detail = require('../api/netease/playlist_detail');
let cloudsearch = require('../api/netease/cloudsearch');
let song_detail = require('../api/netease/song_detail');
let lyric = require('../api/netease/lyric');
let album = require('../api/netease/album');
let artist_songs = require('../api/netease/artist_songs');
let playlist_catlist = require('../api/netease/playlist_catlist');
let top_playlist = require('../api/netease/top_playlist');
let toplist = require('../api/netease/toplist');
let login_cellphone = require('../api/netease/login_cellphone');
let login_status = require('../api/netease/login_status');

export async function top_play_list_163(f){
  //console.log('netease');
   await topPlayList({}).then((r) => {
    //console.log(r)
     let result = []
     for (let playlist of r.playlists) {
       result.push(deal163Result(playlist))
     }
     ////console.log("@@@163",result.length)
     f(result)
   })
}

function deal163Result(data){
  if(data.creator === undefined){
    ////console.log(data)
  }
  let {name,id,coverImgUrl:imgUrl,creator:{nickname : auth = ""} = ""} = data;



  return {
    "name":name,
    "id":id,
    "img":imgUrl,
    "auth":auth,
    "from":'163'
  }
}

export async function get163PlayListDetail(id,f){
  id = id.toString();
  await playlist_detail({id:id}).then((r) => {
    //console.log(r);
    ////console.log(r.data.playlist)
    let result = deal163DetailResult(r.playlist)
    ////console.log(result)
    f(result)
  })
}
function deal163DetailResult(data){

  let {creator:{nickname:user},name, id, description,tags, coverImgUrl:img,playCount,subscribedCount} = data;
  let {tracks} = data;
  let r = tracks.map((i) => {
    let ts = i.dt;
    ts = ts / 1000;
    let min = Math.floor(ts/60);
    let sec = Math.floor(ts - min*60);
    if(min < 10){
      min = '0' + min;
    }
    if(sec < 10){
      sec = '0' + sec;
    }

    return{
      'id':i.id,
      'times' : `${min} : ${sec}`,
      'name' : i.name,
      'singer' : i.ar[0].name,
      'album' : i.al.name,
      'img': i.al.picUrl,
      'from':'163'
    }
  })


  return {
    user:user,
    tags:tags,
    name:name,
    id:id,
    description:description,
    img:img,
    playCount:playCount,
    subscribedCount:subscribedCount,
    list:r
  }
}


export async function get163Search(keywords,offset,limit,type, f){


  await cloudsearch({keywords:keywords,type:type,offset:offset,limit:limit}).then((r) => {
    if(type === 1 || type === '1'){
      //console.log(r)
      let result = deal163SearchSongsResult(r.result)
      let count = r.result?.songCount || 0
      f({v:result,count:count})
    }else if(type === 100 || type === '100'){
      //console.log(r)
      let result = deal163SearchSingersResult(r)
      f(result)
    }else if(type === 1000 || type === '1000'){
      //console.log(r)
      let result = deal163SearchPlayListResult(r)
      f(result)
    }else if(type === 10 || type === '10'){
      //console.log(r)
      let result = deal163SearchAlbumResult(r)
      f(result)
    }
  })
}
function deal163SearchSongsResult(data){

  let {songs} = data;
  let r = songs.map((i) => {
    let ts = i.dt;
    ts = ts / 1000;
    let min = Math.floor(ts/60);
    let sec = Math.floor(ts - min*60);
    if(min < 10){
      min = '0' + min;
    }
    if(sec < 10){
      sec = '0' + sec;
    }

    return{
      'id':i.id,
      'times' : `${min} : ${sec}`,
      'name' : i.name,
      'singer' : i.ar[0].name,
      'album' : i.al.name,
      'img': i.al.picUrl,
      'from' : '163'
    }
  })
  return r

}
function deal163SearchSingersResult(data){

  ////console.log(data)
  let result = data.result || {artistCount:0,artists:[{}]}
  let map = result.artists.map((r) => {

    return {
      id:r.id,
      name: r.name,
      img: r.picUrl,
      from:'163'
    }
  });
  return map
}

function deal163SearchPlayListResult(data){
  ////console.log(data)
  let als = data.result.playlists || []
  return als.map((r) => {

    return {
      "name":r.name,
      "id":r.id,
      "imgUrl":r.coverImgUrl,
      "auth":r.creator.nickname,
      "from":'163'
    }

  })



}

function deal163SearchAlbumResult(data){
  ////console.log(data)
  let als = data.result.albums || []
  return als.map((r) => {

    return {
      "name":r.name,
      "id":r.id,
      "img":r.picUrl,
      "auth":r.artist.name,
      "from":'163'
    }

  })



}

export async function get163PlayMusic(id,f){
  await song_detail({ids:id.toString()}).then((r) => {
    //console.log(r);
    if(!r.songs[0]){
      f(-1)
    }else {
      let result = deal163PlayMusicResult(r.songs[0])
      f(result)
    }
  })

}
function deal163PlayMusicResult(data){

  let {id, name : title} = data
  let info = data.ar[0].name
  let img = data.al.picUrl
  let resource = 'https://music.163.com/song/media/outer/url?id='+id+'.mp3';
  let ts = data.dt;
  ts = ts / 1000;
  let min = Math.floor(ts/60);
  let sec = Math.floor(ts - min*60);
  if(min < 10){
    min = '0' + min;
  }
  if(sec < 10){
    sec = '0' + sec;
  }
  let time = `${min} : ${sec}`;

  return {
    id:id,
    title:title,
    info:info,
    resource:resource,
    from:'163',
    time:time,
    img:img
  }
}
export async function get163lyric(id,f){
  await lyric({id:id}).then((r) => {
    //console.log(r)
    let result = deal163lyricResult(r)
    //console.log(result);
    f(result)
  })

}
function deal163lyricResult(data){

  return data.lrc.lyric || ''

}

export async function get163AlbumDetail(id,f){

  await album({id:id}).then((r) => {
    if(r.code === 20001){
      return new Promise((resolve, reject) => {
        reject('err');
      })
    }
    ////console.log(r.body)
    let result = deal163AlbumDetailResult(r)

    f(result)
  }).catch(() => {

    return new Promise((resolve, reject) => {
      reject('err');
    })

  })
  // await axios.get('/163api/album?id='+id).then((r) => {
  //
  //     //console.log(r.body)
  //     let result = deal163AlbumDetailResult(r.body)
  //
  //     f(result)
  // })
}
function deal163AlbumDetailResult(data){
  let tracks = data.songs || [];
  let r = tracks.map((i) => {
    let ts = i.dt;
    ts = ts / 1000;
    let min = Math.floor(ts/60);
    let sec = Math.floor(ts - min*60);
    if(min < 10){
      min = '0' + min;
    }
    if(sec < 10){
      sec = '0' + sec;
    }

    return{
      'id':i.id,
      'times' : `${min} : ${sec}`,
      'name' : i.name,
      'singer' : i.ar[0].name,
      'album' : i.al.name,
      from:'163'
    }
  })


  return r
}
export async function get163SongsBySinger(id,offset,limit,f){

  await artist_songs({id:id.toString(),offset:offset.toString(),limit:limit.toString()}).then((r) => {

    //console.log(r);
    let result = dealSongBySinger(r);
    f(result);
  })

}
function dealSongBySinger(data){
    let list = data.songs;
    let result = list.map((i) => {

      let ts = i.dt;
      ts = ts / 1000;
      let min = Math.floor(ts/60);
      let sec = Math.floor(ts - min*60);
      if(min < 10){
        min = '0' + min;
      }
      if(sec < 10){
        sec = '0' + sec;
      }
      return{
        'id':i.id,
        'times' : `${min} : ${sec}`,
        'name' : i.name,
        'singer' : i.ar[0].name,
        'album' : i.al.name,
        from:'163'
      }

    })
    return {v:result,count:data.total};
}
export async function get163Catlist(f){
  await playlist_catlist({}).then((r) => {

    //console.log(r)
    let result = deal163Catlist(r)
    //console.log(result);
    f(result)

  }).catch(() => {

    return new Promise((resolve, reject) => {
      reject('err');
    })

  })
  // await axios.get('/163api/playlist/catlist').then((r) => {
  //
  //     //console.log(r.body)
  //     let result = deal163Catlist(r.body)
  //
  //     f(result)
  // })
}
function deal163Catlist(data){
  let cat = [];
  let i = 0;
  for (const e of Object.values(data.categories)) {

    cat[i++] = {'name':e,
      'v':[]
    };
  }

  let subs = data.sub || []
  for (const s of subs) {
    cat[s.category].v.push(s.name);
  }
  ////console.log(cat)
  return cat;
}
export async function get163CatPlayList(cat,offset,limit,f){
  await top_playlist({limit:limit,offset:offset,cat:cat}).then((r) => {
    //console.log(r)
    let result = deal163CatResult(r)
    let count = r.total
    //console.log(result);
    f({v:result,count:count})
  }).catch(() => {

    return new Promise((resolve, reject) => {
      reject('err');
    })

  })
  // await axios.get(`/163api/top/playlist?limit=${limit}&offset=${offset}&cat=${cat}`).then((r) => {
  //     //console.log(r.body)
  //     let result = deal163CatResult(r.body)
  //     let count = r.body.total
  //     f({v:result,count:count})
  // })
}
function deal163CatResult(data){
  let playlists = data.playlists || []
  return playlists.map((r) => {

    return {
      "name":r.name,
      "id":r.id,
      "imgUrl":r.coverImgUrl,
      "auth":r.creator.nickname,
      "from":'163'
    }

  })
}


export async function get163TopList(f){
  await toplist({}).then((r) => {
    //console.log(r)
    let result = deal163TopResult(r)

    f(result)
  }).catch(() => {

    return new Promise((resolve, reject) => {
      reject('err');
    })

  })
  // await axios.get(`/163api/toplist`).then((r) => {
  //     //console.log(r.body)
  //     let result = deal163TopResult(r.body)
  //
  //     f(result)
  // })
}
function deal163TopResult(data){
  let playlists = data.list || []
  return playlists.map((r) => {

    return {
      "name":r.name,
      "id":r.id,
      "img":r.coverImgUrl,
      "auth":r.description,
      "from":'163'
    }

  })
}
export async function login163(phone,pwd,f){
  await login_cellphone({phone:phone,password:pwd}).then((r) => {

      f(r.body?.cookie || -1)

  })
}
export async function login163Status(f){
  await login_status({}).then((r) => {
    r = r.body.data;
    if(r.account?.userName){
      //console.log('有');
      f(r.account?.userName)
    }else {
      f(-1);
    }
  })
}
